package cn.pfund.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Format {

	public static String null2Blank(String str) {
		if (str == null)
			return "";
		else
			return str;
	}

	public static String null2Blank(Object str) {
		String result = "";
		if (str == null) {
			return result;
		}
		return str.toString();
	}

	public static int str2Int(String str) {
		int intVal;
		try {
			intVal = Integer.parseInt(str);
		} catch (Exception e) {
			intVal = -1;
		}
		return intVal;
	}

	public static int null2Zero(Object obj) {
		int result = 0;
		if (obj == null) {
			return result;
		}
		try {
			Integer iObj = (Integer) obj;
			result = iObj.intValue();
		} catch (Exception e) {
			result = 0;
		}
		return result;
	}

	public static int null2Zero(String str) {
		int intTmp;
		intTmp = str2Int(str);
		if (intTmp == -1)
			return 0;
		else
			return intTmp;
	}

	public static String null2bsp(String str) {
		if (str == null)
			return "&nbsp;";
		else
			return str;
	}

	public static String shortStr(String name, int len) {
		String strName = Format.null2Blank(name);
		if (strName.length() > len)
			strName = strName.substring(0, len) + "...";
		return strName;
	}

	public static boolean isBlank(String str) {

		if (str == null || str.equals("")) {
			return true;

		} else {
			return false;
		}

	}

	public static String setStrings(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen >= len)
				return s + "...";
		}
		return s;
	}

	public static String setStrings2(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen >= len)
				return s;
		}
		return s;
	}

	public static String setStrings3(String str, int len) {
		int strlen = 0;
		String s = "";

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > 128)
				strlen += 2;
			else
				strlen++;
			s += str.charAt(i);
			if (strlen > len)
				return s + "…";
		}
		return s;
	}
	
	public static String encodeURI(String str, String charsetName) {
		charsetName = (charsetName == null || charsetName.equals("")) ? "UTF-8" : charsetName;
		String s=str;
		if(s==null || s.equals("")) return s;
		try {
			s=URLEncoder.encode(str, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}
}
